// Copyright 2023 Dolthub, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package utils

import (
	"fmt"
	"strconv"
	"strings"
	"sync/atomic"
)

// uniqueAliasCounter is used to create unique aliases. Aliases are required by GMS when some expressions are contained
// within an AliasedTableExpr. Postgres does not have this restriction, so we must do this for compatibility.
var uniqueAliasCounter atomic.Uint64

// uniqueAliasPrefix is the prefix given to aliases that have been generated by GenerateUniqueAlias.
var uniqueAliasPrefix = "doltgres!|!alias!|_"

// GenerateUniqueAlias generates a unique alias. This is thread-safe.
func GenerateUniqueAlias() string {
	return fmt.Sprintf("%s%d", uniqueAliasPrefix, uniqueAliasCounter.Add(1))
}

// IsGeneratedAlias returns whether the given alias was generated using GenerateUniqueAlias.
func IsGeneratedAlias(alias string) bool {
	if strings.HasPrefix(alias, uniqueAliasPrefix) && len(alias) > len(uniqueAliasPrefix) {
		aliasDigits := alias[len(uniqueAliasPrefix):]
		if _, err := strconv.ParseUint(aliasDigits, 10, 64); err == nil {
			return true
		}
	}
	return false
}
